package com.liang.pcc.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.fastjson2.JSON;
import com.liang.pcc.domain.HarmonicData;
import com.liang.pcc.excel.model.MeasurementPoint;
import com.liang.pcc.excel.BaseExcelListener;
import com.liang.pcc.service.MeasurementPointService;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.function.BiConsumer;

@Slf4j
public class HarmonicCurrentListener extends BaseExcelListener<Map<Integer, String>> {

    private final MeasurementPointService measurementPointService;
    private final Long fileId;
    private final Long userId;

    private final List<MeasurementPoint> points = new ArrayList<>();
    private final List<Integer> validColumns = new ArrayList<>(); // 存储有效列索引

    // 解析状态机
    private enum ParseState {HEADER, VOLTAGE, CAPACITY, HARMONIC_HEADER, HARMONIC}

    private ParseState currentState = ParseState.HEADER;

    public HarmonicCurrentListener(MeasurementPointService measurementPointService, CountDownLatch latch, Long fileId, Long userId) {
        super(latch);
        this.measurementPointService = measurementPointService;
        this.fileId = fileId;
        this.userId = userId;
    }

    @Override
    public void invoke(Map<Integer, String> rowMap, AnalysisContext context) {
        switch (currentState) {
            case HEADER -> {
                processHeader(rowMap);
                currentState = ParseState.VOLTAGE;
            }
            case VOLTAGE -> {
                processVoltage(rowMap);
                currentState = ParseState.CAPACITY;
            }
            case CAPACITY -> {
                processCapacity(rowMap);
                currentState = ParseState.HARMONIC_HEADER;
            }
            case HARMONIC_HEADER -> {
                // 跳过谐波数据表头行（不做任何处理）
                log.info("跳过谐波表头行：{}", rowMap.values());
                currentState = ParseState.HARMONIC;
            }
            default -> processHarmonic(rowMap);
        }
    }

    private void processHeader(Map<Integer, String> data) {
        log.info("实测点行数据：{}", JSON.toJSONString(data));
        // 识别有效列（排除首列，且内容不为空）
        data.forEach((colIndex, value) -> {
            if (colIndex > 0 && value != null && !value.trim().isEmpty()) {
                validColumns.add(colIndex);
                points.add(MeasurementPoint.builder()
                        .pointName(value)
                        .harmonics(new ArrayList<>())
                        .fileId(fileId)
                        .userId(userId)
                        .build());
                log.info("识别到有效实测点：{}，列索引：{}", value, colIndex);
            }
        });
        // 按列索引排序保证顺序
        validColumns.sort(Integer::compareTo);
    }

    private void processVoltage(Map<Integer, String> data) {
        log.info("电压等级：{}", JSON.toJSONString(data));
        processNumericData(data, "电压等级", MeasurementPoint::setVoltageLevel);
    }

    private void processCapacity(Map<Integer, String> data) {
        log.info("最小短路容量：{}", JSON.toJSONString(data));
        processNumericData(data, "短路容量", MeasurementPoint::setShortCircuitCapacity);
    }

    // 通用数值处理方法
    private void processNumericData(Map<Integer, String> data, String fieldName, BiConsumer<MeasurementPoint, BigDecimal> setter) {
        for (int i = 0; i < validColumns.size(); i++) {
            Integer colIndex = validColumns.get(i);
            String valueStr = data.get(colIndex);

            if (valueStr == null || valueStr.trim().isEmpty()) {
                log.warn("{}为空，实测点：{}", fieldName, points.get(i).getPointName());
                continue;
            }

            try {
                BigDecimal value = new BigDecimal(valueStr.trim());
                setter.accept(points.get(i), value);
            } catch (NumberFormatException e) {
                log.error("无效的{}值：{}，实测点：{}", fieldName, valueStr, points.get(i).getPointName());
            }
        }
    }

    private void processHarmonic(Map<Integer, String> data) {
        log.info(" 谐波数据:{}", JSON.toJSONString(data));
        Integer order = Integer.valueOf(data.get(0));

        // 每组数据占3列
        for (int i = 0; i < points.size(); i++) {
            int baseCol = 1 + i * 3;

            HarmonicData hd = HarmonicData.builder()
                    .harmonicOrder(order)
                    .measuredValue(new BigDecimal(data.get(baseCol)))
                    .allowedValue(new BigDecimal(data.get(baseCol + 1)))
                    .checkResult(data.get(baseCol + 2))
                    .fileId(fileId)
                    .userId(userId)
                    .build();

            points.get(i).getHarmonics().add(hd);
        }
        log.info(" HarmonicData:{}", JSON.toJSONString(points));
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        measurementPointService.saveBatchWithHarmonics(points);
        super.doAfterAllAnalysed(context);
        log.info("谐波电流数据导入完成，共处理{}个监测点", points.size());
    }
}